package com.gujiangbo.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Lock;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/3/14 20:34
 * @Version: 1.0
 * @Description: 使用java中的Condition实现线程的等待与唤醒 await signal ,该两个方法必须要与lock配套使用，否则会报非法监视器异常
 */
public class JavaCondition {
    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) {

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t coming in .");
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

            System.out.println(Thread.currentThread().getName() + "\t 被唤醒..");
        }, "A").start();


        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t 开始唤醒...");
                condition.signal();
            } finally {
                lock.unlock();
            }
        }, "B").start();
    }

}
